package com.mj.common.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PostSmsUtil {
	
	private static String operId = "famei";
	private static String operPass = "famei";
	
	public static String sendMessage(String content,String phoneNum){
		try {
			String urlstr = "http://221.179.180.156:9836/HttpApi_Simple/submitMessage";

			URL url = new URL(urlstr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();

			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("POST");

			conn.setRequestProperty("Connection", "close");
			conn.setReadTimeout(10000);
			conn.setConnectTimeout(5000);

			conn.connect();
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String currentTime = sdf.format(new Date());
			
			String inputXML = "<?xml version=\"1.0\" encoding=\"GBK\"?>"
					+ "<CoreSMS>" + "<OperID>" + operId +"</OperID>"
					+ "<OperPass>" + operPass + "</OperPass>"
					+ "<Action>Submit</Action>" + "<Category>0</Category>"
					+ "<Body>" + "<SendTime>" + currentTime + "</SendTime>"
					+ "<AppendID></AppendID>" + "<Message>"
					+ "<DesMobile>" + phoneNum + "</DesMobile>"
					+ "<Content>" + content + "</Content>"
					+ "<SendType></SendType>" + "</Message>" +

					"</Body>" + "</CoreSMS>";

			byte[] b = inputXML.getBytes("gbk");
			OutputStream os = conn.getOutputStream();
			DataOutputStream dos = new DataOutputStream(os);
			dos.write(b);
			dos.flush();
			os.close();

			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			InputStream is = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			int r = bis.read();
			while (r >= 0) {
				bos.write(r);
				r = bis.read();
			}
			String outputXML = new String(bos.toByteArray(), "UTF-8");
			is.close();

			conn.disconnect();
			return outputXML;
		} catch (IOException ex2) {
			System.out.println(" exe IOException:" + ex2.toString());
			return null;
		}
	}
	
	
}
